package org.apache.solr.dataimport.handler.scheduler;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SolrDataImportProperties {
	private static final Logger logger = LoggerFactory.getLogger(SolrDataImportProperties.class);
	
	private Properties properties;

	public static final String SYNC_ENABLED = "syncEnabled";
	public static final String SYNC_CORES = "syncCores";
	public static final String SERVER = "server";
	public static final String PORT = "port";
	public static final String WEBAPP = "webapp";
	public static final String PARAMS = "params";
	public static final String INTERVAL = "interval";

	private String autoDeltaImportConfPath;
	private long lastModified;

	public SolrDataImportProperties() {
		// loadProperties(true);
	}

	public SolrDataImportProperties(String autoDeltaImportConfPath) {
		logger.info("auto delta dataimport config path: {}", autoDeltaImportConfPath);
		this.autoDeltaImportConfPath = autoDeltaImportConfPath;
		loadProperties(true);
	}

	public void loadProperties(boolean force) {
		try {
			if (force || properties == null) {
				properties = new Properties();

				File dataImportProperties = new File(autoDeltaImportConfPath,
						"dataimport.properties");
				lastModified = dataImportProperties.lastModified();
				FileInputStream fis = new FileInputStream(dataImportProperties);
				properties.load(fis);
			}
		} catch (FileNotFoundException fnfe) {
			logger.error(
					"Error locating DataImportScheduler dataimport.properties file",
					fnfe);
		} catch (IOException ioe) {
			logger.error(
					"Error reading DataImportScheduler dataimport.properties file",
					ioe);
		} catch (Exception e) {
			logger.error("Error loading DataImportScheduler properties", e);
		}
	}
	
	public boolean isModified() {
		File file = new File(autoDeltaImportConfPath,
				"dataimport.properties");
		return file.lastModified() > lastModified;
	}

	public String getProperty(String key) {
		return properties.getProperty(key);
	}
}
